import * as vscode from 'vscode';
import * as path from 'path';
import { componentCompileLogger } from "./logger/componentCompileLogger";
import { getRepoPath } from './utils/commonUtils';
import { prebuildDownloadLogger } from './logger/prebuildDownloadLogger';
import { registerTerminal } from './utils/terminalManager';

export async function prebuildDownload(args: any[], withDownloadSdk: boolean) {
    prebuildDownloadLogger.clear();

    if (args.length === 0) {
        vscode.window.showErrorMessage('No args provided, please see the log for more information');
        componentCompileLogger.errorWithStack('No args provided');
        return;
    }

    const uri = args[0] as vscode.Uri;
    if (!uri || typeof uri.fsPath !== 'string') {
        vscode.window.showErrorMessage('Invalid URI provided, please see the log for more information');
        componentCompileLogger.errorWithStack('Invalid URI provided');
        return;
    }

    const filePath = uri.fsPath;
    componentCompileLogger.info(`bundle.json's path is : ${filePath}`);
    const pathParts = filePath.split(/[/\\]/);
    const parentFolderName = pathParts.length >= 2 ? pathParts.slice(-2, -1)[0] : '';

    if (!parentFolderName) {
        vscode.window.showErrorMessage('Could not extract parent folder name from path, please see the log for more information');
        componentCompileLogger.errorWithStack('Could not extract parent folder name from path');
        return;
    }
    componentCompileLogger.info(`parentFolderName is : ${parentFolderName}`);

    // 处理路径分隔符，兼容Windows和Unix
    const dirPath = path.dirname(filePath);
    // Find the root directory containing .repo folder
    const repoRootPath = getRepoPath(dirPath);
    if (!repoRootPath) {
        vscode.window.showErrorMessage('Could not find .repo directory in any parent folder, please see the log for more information');
        componentCompileLogger.errorWithStack('Could not find .repo directory in any parent folder');
        return;
    }

    vscode.window.showInformationMessage(`[${parentFolderName}]: Prebuild download process has started in the terminal.`);
    executeAndLogCommand(withDownloadSdk, parentFolderName, repoRootPath);
}

/**
 * 执行命令并记录日志
 * @param withDownloadSdk 是否下载sdk
 * @param parentFolderName bundle.json所在目录的父文件夹名称
 * @param repoRootPath 仓库根目录
 */
function executeAndLogCommand(withDownloadSdk: boolean, parentFolderName: string, repoRootPath: string) {
    let commandStr = `bash ./build/prebuilts_config.sh`;

    if (withDownloadSdk) {
        commandStr += ` --download-sdk`;
    }

    componentCompileLogger.info(`command is ${commandStr}`);

    const terminal = vscode.window.createTerminal({
        name: `Prebuild Download: ${parentFolderName}`,
        cwd: repoRootPath
    });
    registerTerminal('prebuild', terminal);

    terminal.show();
    terminal.sendText(commandStr);
}